package com.banban.user.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.banban.user.domain.SysDictDetailEntity;
import com.banban.user.domain.SysDictEntity;
import com.banban.user.dto.DeleteDTO;
import com.banban.user.exception.BusinessException;
import com.banban.user.service.SysDictDetailService;
import com.banban.user.service.SysDictService;
import com.banban.user.vo.DataResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@Api(tags = "字典管理")
@RestController
@RequestMapping("/sysDict")
public class SysDictController {
    @Resource
    private SysDictService sysDictService;
    @Resource
    private SysDictDetailService sysDictDetailService;


    @ApiOperation(value = "新增")
    @PostMapping("/add")
    public DataResult add(@RequestBody @Valid SysDictEntity sysDict) {
        SysDictEntity q = sysDictService.getOne(Wrappers.<SysDictEntity>lambdaQuery().eq(SysDictEntity::getName, sysDict.getName()));
        if (q != null){
            throw new BusinessException("字典名称已存在");
        }
        sysDictService.save(sysDict);
        return DataResult.success();
    }

    @ApiOperation(value = "删除")
    @PostMapping("/delete")
    public DataResult delete(@RequestBody DeleteDTO dto) {
        sysDictService.removeByIds(dto.getIds());
        //删除detail
        sysDictDetailService.remove(Wrappers.<SysDictDetailEntity>lambdaQuery().in(SysDictDetailEntity::getDictId, dto.getIds()));
        return DataResult.success();
    }

    @ApiOperation(value = "更新")
    @PostMapping("/update")
    public DataResult update(@RequestBody @Valid SysDictEntity sysDict) {
        sysDictService.updateById(sysDict);
        return DataResult.success();
    }

    @ApiOperation(value = "查询分页数据")
    @PostMapping("/listByPage")
    public DataResult findListByPage(@RequestBody SysDictEntity sysDict) {
        LambdaQueryWrapper<SysDictEntity> queryWrapper = Wrappers.lambdaQuery();
        //查询条件示例
        if (!StringUtils.isEmpty(sysDict.getName())) {
            queryWrapper.like(SysDictEntity::getName, sysDict.getName());
            queryWrapper.or();
            queryWrapper.like(SysDictEntity::getRemark, sysDict.getRemark());
        }
        queryWrapper.orderByAsc(SysDictEntity::getName);
        return DataResult.success(sysDictService.page(sysDict.getQueryPage(), queryWrapper));
    }

}